<template>
  <!-- 列表 -->
  <ContentWrap>
    <div style="height: 50px">
      <el-button
        v-hasPermi="['orderReport:orderCostProject:export']"
        type="primary"
        :loading="exportLoading"
        @click="saveData"
      >
        保存
      </el-button>
      <el-button
        v-hasPermi="['orderReport:orderCostProject:export']"
        type="primary"
        :loading="exportLoading"
        @click="submitData()"
      >
        提交
      </el-button>

      <el-button
        @click="addData"
        v-hasPermi="['orderReport:orderCostProject:update']"
        type="primary"
      >
        新增行
      </el-button>
      <el-button @click="close">关闭</el-button>
    </div>
    <el-table ref="multipleTableRef" border :height="tableHeight" :data="list" row-key="id">
      <el-table-column label="序号" align="center" type="index" fixed="left" width="80" />
      <el-table-column align="left" width="180">
        <template #header>
          <span>部门</span>
        </template>
        <template #default="scope">
          <el-select
            v-model="scope.row.dictDeptName"
            placeholder="请选择部门"
            required
            class="!w-140px"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions(DICT_TYPE.DICT_DEPT_WORD)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="left" width="180">
        <template #header>
          <span>登记事项</span>
        </template>
        <template #default="scope">
          <el-select
            v-model="scope.row.dictMatter"
            placeholder="请选择登记事项"
            required
            class="!w-140px"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions(DICT_TYPE.DICT_MATTER)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="客户名称"
        header-align="left"
        align="left"
        prop="customerName"
        min-width="200px"
      />
      <el-table-column align="left" width="180" :class="'custom-header'">
        <template #header>
          <span style="color: red" v-if="isDisabled">*</span>
          <span>产品编号</span>
        </template>
        <template #default="scope">
          <div class="select-wrapper">
            <el-select
              v-model="scope.row.productNumber"
              placeholder="请选择产品编号"
              class="!w-140px"
              filterable
              remote
              :remote-method="filterOptions1"
              @change="handleChangePd(scope.$index)"
            >
              <el-option
                v-for="channel in filteredOptions1"
                :key="channel.productNumber"
                :value="channel.productNumber"
                :label="channel.productNumber"
              />
            </el-select>
            <span class="search-icon" @click="handleSearch(scope.$index)">
              <Icon icon="ep:search" />
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="left" width="180">
        <template #header>
          <span>登记月份</span>
        </template>
        <template #default="scope">
          <el-date-picker
            v-model="scope.row.registerMonth"
            type="month"
            placeholder="请选择登记月份"
            style="width: 150px"
            class="!w-140px"
            value-format="YYYY-MM"
          />
        </template>
      </el-table-column>
      <el-table-column label="出差时间" align="center" width="220">
        <el-table-column align="left" width="180">
          <template #header>
            <span>起始时间</span>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.startDate"
              type="date"
              placeholder="请选择起始时间"
              style="width: 150px"
              class="!w-140px"
              value-format="YYYY-MM-DD"
            />
          </template>
        </el-table-column>
        <el-table-column align="left" width="180">
          <template #header>
            <span>结束时间</span>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.endDate"
              type="date"
              placeholder="请选择结束时间"
              style="width: 150px"
              class="!w-140px"
              value-format="YYYY-MM-DD"
            />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="left" width="180" :class="'custom-header'">
        <template #header>
          <span>天数</span>
        </template>
        <template #default="scope">
          <el-input
            v-model="scope.row.numberOfDays"
            type="number"
            v-bind:only-number="true"
            class="!w-140px"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="left"
        width="180"
        type="number"
        v-bind:only-number="true"
        :class="'custom-header'"
      >
        <template #header>
          <span>人数</span>
        </template>
        <template #default="scope">
          <el-input
            v-model="scope.row.numberOfPeople"
            type="number"
            v-bind:only-number="true"
            class="!w-140px"
          />
        </template>
      </el-table-column>
      <el-table-column align="left" width="180" :class="'custom-header'">
        <template #header>
          <span>人工费(元)</span>
        </template>
        <template #default="scope">
          <el-input
            v-model="scope.row.costOfLabor"
            type="number"
            v-bind:only-number="true"
            class="!w-140px"
            @input="change(scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column align="left" width="180" :class="'custom-header'">
        <template #header>
          <span>报销经办人</span>
        </template>
        <template #default="scope">
          <el-input v-model="scope.row.applyOfPeople" class="!w-140px" />
        </template>
      </el-table-column>
      <el-table-column label="伙食费(元)" align="center" width="220">
        <el-table-column align="right" width="180" :class="'custom-header'">
          <template #header>
            <span>中餐</span>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.lunch"
              class="!w-140px"
              type="number"
              v-bind:only-number="true"
              :disabled="type"
              @input="change(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column align="right" width="180" :class="'custom-header'">
          <template #header>
            <span>晚餐</span>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.supper"
              class="!w-140px"
              type="number"
              v-bind:only-number="true"
              :disabled="type"
              @input="change(scope.$index)"
            />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="right" width="180" :class="'custom-header'">
        <template #header>
          <span>住宿(元)</span>
        </template>
        <template #default="scope">
          <el-input
            v-model="scope.row.stay"
            class="!w-140px"
            type="number"
            v-bind:only-number="true"
            :disabled="type"
            @input="change(scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column align="right" width="180" :class="'custom-header'">
        <template #header>
          <span>补贴住宿</span>
        </template>
        <template #default="scope">
          <el-input
            v-model="scope.row.staySubsidy"
            class="!w-140px"
            type="number"
            v-bind:only-number="true"
            :disabled="type"
            @input="change(scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column align="right" width="180" :class="'custom-header'">
        <template #header>
          <span>车费</span>
        </template>
        <template #default="scope">
          <el-input
            v-model="scope.row.fareCar"
            class="!w-140px"
            type="number"
            v-bind:only-number="true"
            :disabled="type"
            @input="change(scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column align="right" width="180" :class="'custom-header'">
        <template #header>
          <span>国外津贴</span>
        </template>
        <template #default="scope">
          <el-input
            v-model="scope.row.allowance"
            class="!w-140px"
            type="number"
            v-bind:only-number="true"
            :disabled="type"
            @input="change(scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column align="right" width="180" :class="'custom-header'">
        <template #header>
          <span>其他费用</span>
        </template>
        <template #default="scope">
          <el-input
            v-model="scope.row.otherCharges"
            class="!w-140px"
            type="number"
            v-bind:only-number="true"
            :disabled="type"
            @input="change(scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="合计"
        header-align="right"
        align="right"
        prop="totalPrice"
        min-width="200px"
      />
      <el-table-column label="状态" header-align="left" align="left" min-width="200px">
        <template #default="scope">
          <dict-tag :type="'dict_cost_status'" :value="scope.row.dictStatus" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        header-align="left"
        align="left"
        prop="createTime"
        min-width="200px"
      />
      <el-table-column
        label="创建人"
        header-align="left"
        align="left"
        prop="creatorName"
        min-width="200px"
      />
      <el-table-column label="操作" header-align="left" align="left" width="120" fixed="right">
        <template #default="scope">
          <el-button link type="danger" @click="deleteRow(scope.$index)">删除行</el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
  <!-- 产品档案列表 -->
  <CustomerProfile ref="formRef" @success="selectData" />
</template>

<script setup lang="ts" name="OrderCost">
  import { useTagsViewStore } from '@/store/modules/tagsView'
  const tagsViewStore = useTagsViewStore()
  const routes = useRouter() // 路由
  const route = useRoute()
  console.log(route)
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import CustomerProfile from './customerProfile.vue'
  import * as productRelationApi from '@/api/orderManagement/productRelation'
  import * as FeeRegistrationApi from '@/api/reportQuery/engineeringDepartmentReport/feeRegistration'
  const message = useMessage() // 消息弹窗
  const { t } = useI18n() // 国际化
  const multipleTableRef = ref()
  const list = ref([]) // 列表的数据
  const { push } = useRouter()
  const tenantOptions = ref<any>([])
  const exportLoading = ref(false) // 导出的加载中
  let filteredOptions1 = ref<any>([])
  //模糊查询
  const filterOptions1 = async (query) => {
    if (query) {
      filteredOptions1 = await tenantOptions.value.filter((option) =>
        option.productNumber.includes(query)
      )
    }
  }
  //搜索图标
  const formRef = ref()
  const handleSearch = async (index) => {
    formRef.value.open(index, list.value[index].productNumber)
  }
  //获取产品档案列表
  const getProductsList = async () => {
    let params = {}
    const data = await productRelationApi.getProductsList(params)
    tenantOptions.value = data.list
  }
  const selectData = async (data) => {
    list.value[data.index.value].productNumber = data.list[0].productNumber
    list.value[data.index.value].productName = data.list[0].productName
    list.value[data.index.value].customerName = data.list[0].customerName
    list.value[data.index.value].customerCode = data.list[0].customerCode
  }
  /**移除行 */
  const deleteRow = (index: number) => {
    list.value.splice(index, 1)
  }
  //新增
  const addData = () => {
    const newRow = {
      dictDeptName: undefined,
      dictMatter: undefined,
      customerName: undefined,
      customerCode: undefined,
      productNumber: undefined,
      registerMonth: undefined,
      startDate: undefined,
      endDate: undefined,
      numberOfDays: undefined,
      numberOfPeople: undefined,
      costOfLabor: undefined,
      applyOfPeople: undefined,
      lunch: undefined,
      supper: undefined,
      stay: undefined,
      staySubsidy: undefined,
      fareCar: undefined,
      allowance: undefined,
      otherCharges: undefined,
      totalPrice: undefined,
      dictStatus: undefined,
      id: undefined
    }
    list.value.push(newRow)
  }
  /**关闭 */
  const close = () => {
    tagsViewStore.delView(routes.currentRoute.value)
    push('/reportQuery/reportQuery/engineeringDepartmentReport/feeRegistration')
  }
  /**保存 */
  const saveData = () => {
    submit(1)
  }

  /**提交 */
  const submitData = () => {
    submit(2)
  }

  const submit = async (flag) => {
    if(!list.value.length) {
      message.error(t('请至少新增一行'))
        return false
    }
    for(let i = 0;i<list.value.length;i++){
      if(!list.value[i].productNumber) {
        message.error(t('产品编号不能为空'))
        return false
      }
    }
    list.value.forEach((item) => {
      item.submitFlag = flag
    })
    await FeeRegistrationApi.saveOrSubmit(list.value)
    message.success(t('common.createSuccess'))
    close()
  }
  /**合计 */
  const change = (index) => {
    let sum = 0
    sum += list.value[index].costOfLabor ? Number(list.value[index].costOfLabor) : 0
    sum += list.value[index].lunch ? Number(list.value[index].lunch) : 0
    sum += list.value[index].supper ? Number(list.value[index].supper) : 0
    sum += list.value[index].stay ? Number(list.value[index].stay) : 0
    sum += list.value[index].staySubsidy ? Number(list.value[index].staySubsidy) : 0
    sum += list.value[index].fareCar ? Number(list.value[index].fareCar) : 0
    sum += list.value[index].allowance ? Number(list.value[index].allowance) : 0
    sum += list.value[index].otherCharges ? Number(list.value[index].otherCharges) : 0
    list.value[index].totalPrice = sum.toFixed(4)
  }
  /** 初始化 **/
  /** 初始化 **/
  const tableHeight = ref(0)
  onMounted(async () => {
    tableHeight.value = document.body.clientHeight - 132 - 127
    getProductsList()
  })
</script>
<style lang="scss" scoped>
  .select-wrapper {
    display: flex;
    align-items: center;
  }

  .search-icon {
    margin-left: -24px; /* 这里的 -24px 是根据 Icon 的宽度进行调整的 */
    cursor: pointer;
    margin-top: 5px;
  }
</style>
